package com.lg.baselibrary.app;

import android.app.Application;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.lg.baselibrary.ExceptionCrashHandler;
import com.lg.baselibrary.utils.upload.FormFile;
import com.lg.baselibrary.utils.upload.MutlUploadUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LiGang on 2017/5/4.
 */

public class ExceptionCrashHandlerApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ExceptionCrashHandler.getInstance().init(this);
        new Thread(){
            @Override
            public void run() {
                uploadCrashFile();
            }
        }.start();

    }
    private void uploadCrashFile(){

        Log.d("ExceptionCrashHandlerAp", "------进入上传崩溃日志流程----------");
        File crashFile = ExceptionCrashHandler.getInstance().getCrashFile();
        if(crashFile == null || !crashFile.exists()){
            Log.d("ExceptionCrashHandlerAp", "------还没有崩溃日志-------");
            return;
        }
//        crashFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +"0" + File.separator + "2017_05_28_14-14-12.txt");
        Log.d("ExceptionCrashHandlerAp", "crashFile.exists():" + crashFile.exists());
        Log.d("ExceptionCrashHandlerAp", "---------开始上传崩溃日志到服务器---------");
        String url = "http://192.168.1.4:8080/MengUpload/UploadServlet";
        List<FormFile> files = new ArrayList<FormFile>();
		/* 内容类型 */
        String contentType = "application/octet-stream";
        FormFile crashformFile = new FormFile(crashFile.getName(), crashFile, "crash_file", contentType);
        files.add(crashformFile);
        /**用来存储向服务器提交的参数**/
        Map<String, String> params = new HashMap<String, String>();//post的StringBody
        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        String deviceId = TelephonyMgr.getDeviceId();
        params.put("deviceId",deviceId);
        params.put("content", "崩溃日志");//帖子内容
        try {
            boolean success = MutlUploadUtil.post(url, params, files);
            if(success){
                Log.d("ExceptionCrashHandlerAp", "上传成功");
                crashFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}